<!--
 @description  经销商档案新建-基础信息
 @fileName BasiInfo.vue
 @author zengqiongying
 @created 2023/04/30 18:05:03
-->
<template>
  <div class="has-foot-pb">
    <Card no-mg :round="false">
      <Cell :modelValue="formData.officeName" title="办事处" placeholder="选择办事处" @right="onSearchOffice" />
      <!-- <template v-if="!!formData.officeCode">
        <Cell :modelValue="formData.officeCode" title="办事处编码" readonly />
        <Cell :modelValue="formData.officeTypeName" title="办事处类别" readonly />
        <Cell :modelValue="formData.personName" title="办事处负责人" readonly />
      </template> -->
      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="formData.officeCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />
        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>
    <Card title="经销商基本信息" no-mg :round="false">
      <Cell
        v-model="formData.customerName"
        title="经销商系统名称"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        inputAlign="right"
      />
      <Cell
        v-model="formData.legalPerson"
        title="经销商姓名"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        inputAlign="right"
      />
      <Cell
        v-model="formData.credentialNo"
        title="经销商身份证号"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        type="tel"
        inputAlign="right"
      />
      <!-- <Cell
        v-model="formData.disAddr"
        title="身份证详细地址"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        inputAlign="right"
      /> -->
      <FieldDateTime
        v-model="formData.cooperateStart"
        title="合作起始日期"
        placeholder="选择合作日期"
        type="date"
        :default-date="formData.cooperateStart"
        :max-date="maxDate"
        :min-date="minDate"
        clear
        required
      />
      <!-- <Cell title="是否缴纳保证金" custom :right="false" required>
        <qmp-switch v-model="formData.isDeposit">
          <template #background>
            <span class="qmp-switch__background"> {{ formData.isDeposit ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell> -->
      <Cell title="是否合伙经营" custom :right="false" required>
        <qmp-switch v-model="formData.isPartnership">
          <template #background>
            <span class="qmp-switch__background"> {{ formData.isPartnership ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell>
      <!-- <Cell title="是否经销商交接" custom :right="false" required>
        <qmp-switch v-model="formData.isMarketConnect" :active-value="1" :inactive-value="0">
          <template #background>
            <span class="qmp-switch__background"> {{ formData.isMarketConnect===1 ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell> -->
      <FieldSelect
        v-model="formData.isMarketConnect"
        title="是否经销商交接"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
        clear
      />
    </Card>
    <Card title="附件上传" no-mg :round="false">
      <Cell title="身份证正反面" is-column custom required :right="false">
        <UploadIdCard
          v-model:front-list="attachment.ACCESS050"
          v-model:back-list="attachment.ACCESS051"
          :objectId="id"
        />
      </Cell>
      <Cell title="资金安全告知函" is-column custom required :right="false">
        <AttachmentUpload v-model="attachment.ACCESS052" type-code="ACCESS052" :limit="1" :objectId="id" />
        <div v-if="attachment.ACCESS052.length === 0">暂无数据</div>
      </Cell>
      <Cell title="签字签章函" is-column custom required :right="false">
        <AttachmentUpload v-model="attachment.ACCESS053" type-code="ACCESS053" :limit="1" :objectId="id" />
        <div v-if="attachment.ACCESS053.length === 0">暂无数据</div>
      </Cell>
      <Cell title="收货地址确认单" is-column custom required :right="false">
        <AttachmentUpload v-model="attachment.ACCESS054" type-code="ACCESS054" :limit="1" :objectId="id" />
        <div v-if="attachment.ACCESS054.length === 0">暂无数据</div>
      </Cell>
    </Card>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSave">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import FieldDateTime from '@/components/FieldDateTime/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'
  import UploadIdCard from '../components/UploadIdCard/index.vue'
  import { detail, createSaveBasic } from '@/apis/dealerMarketing/NewArchive'
  import { initFormData, parseTime } from '@/utils'
  import { validIDCard } from '@/utils/validate'
  import GetKeyboardMixin from '@/utils/useKeyboard'

  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerNewArchiveBasicInfo',
    components: { Card, FieldSelect, FieldDateTime, Cell, AttachmentUpload, UploadIdCard },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        maxDate: new Date(),
        minDate: new Date(),
        formData: {
          id: '',
          code: '',

          officeCode: '',
          officeName: '',
          officeTypeCode: '',
          officeTypeName: '', // 办事处类别
          personName: '', //办事处负责人
          personCode: '', //办事处责任编码

          isOtherReceiveManagerKnow: '0', //是否需要其他业务客户经理接收知晓
          receiveManagerCode: '', // 接收经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeName: '',
          receiveManagerTypeCode: '',
          submitAnOpinion: '', //提报意见

          customerName: '',
          legalPerson: '',
          credentialNo: '',
          disAddr: '',
          cooperateStart: '',
          // isDeposit: false,
          isPartnership: false,
          isMarketConnect: ''
        },
        attachment: {
          ACCESS050: [],
          ACCESS051: [],
          ACCESS052: [],
          ACCESS053: [],
          ACCESS054: []
        }
      })

      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()

      const onChangeOffice = (d: any) => {
        const officeData = {
          officeCode: d?.code || '',
          officeName: d?.name || '',
          officeTypeCode: d?.officeTypeCode || '',
          officeTypeName: d?.officeTypeName || '',
          personCode: d?.principalCode || '',
          personName: d.principalName || ''
        }
        datas.formData = { ...datas.formData, ...officeData }
        onChangeReceiveManager(null)
      }
      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }
      const getDetail = () => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          const d = res.data
          initFormData(d, datas.formData)
          if (datas.formData.cooperateStart) {
            datas.formData.cooperateStart = parseTime(datas.formData.cooperateStart, '{y}-{m}-{d}')
          }
        })
      }
      /* const getFiles = (fileList: any, modelId: any, filterData = false) => {
        fileList = filterData ? fileList.filter((e: any) => e.flag !== 'data') : fileList
        return fileList.map((file: any) => {
          const data = { ...file.response.data }
          if (typeof modelId === 'string') {
            data.modelId = modelId
          } else if (typeof modelId === 'boolean' && modelId) {
            delete data.modelId
          }
          return data
        })
      } */
      const getPostData = () => {
        const data = { ...datas.formData }
        // data.isDeposit = data.isDeposit ? 1 : 0
        data.isPartnership = data.isPartnership ? 1 : 0
        data.isMarketConnect = ['1', 1].includes(data.isMarketConnect) ? 1 : 0
        const attachment = datas.attachment
        data.attachmentDTOS = [
          ...attachment.ACCESS050,
          ...attachment.ACCESS051,
          ...attachment.ACCESS052,
          ...attachment.ACCESS053,
          ...attachment.ACCESS054
        ]
        return data
      }
      const onSave = () => {
        const data = getPostData()
        if (!validIDCard(data.credentialNo)) {
          proxy.$toast('经销商身份证号码无效')
          return
        }
        data.id = datas.id
        createSaveBasic(data).then((res: any) => {
          proxy.$SimpleEvents.emit('refreshCustomerNewArchiveEditInfo')
          nextTick(() => {
            $router.goBack()
          })
        })
      }
      const onSearchOffice = () => {
        proxy.$SimpleEvents.registerEvent('NewArchiveAddSetOffice', (data: any) => {
          onChangeOffice(data)
        })
        $router.push({
          path: '/search/Office',
          query: {
            name: 'NewArchiveAddSetOffice'
          }
        })
      }

      const onSearchCustomerManager = () => {
        const officeCode = datas.formData.officeCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('NewArchiveAddSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/personManager',
          query: {
            name: 'NewArchiveAddSetManager',
            office: officeCode
          }
        })
      }

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerNewArchiveEdit'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })

      const date = new Date()
      const sDate = new Date().setMonth(date.getMonth() - 1)
      const eDate = new Date().setDate(date.getDate() + 1)
      datas.minDate = new Date(sDate)
      datas.maxDate = new Date(eDate)

      getDetail()

      return {
        ...toRefs(datas),
        onSearchOffice,
        onSearchCustomerManager,
        onSave
      }
    }
  }
</script>
<style lang="less" scoped></style>
